package com.likerSai;

import java.util.Arrays;

/**
 * 最接近的三数之和
 *
 * 第一次的思路有问题，三元数组在坐标轴上从左向右移动和是单调增的，但是考虑到有0存在的话不能简单的这样处理，跨过0的三项和有可能更接近于目标值
 * @author sun.ye
 * @since 2021-07-16 11:49
 */
public class ThreeSumClosest {


    public static void main(String[] args) {
        int result = threeSumClosest(   new int[]{-100,-98,-2,-1}   ,-101);
        System.out.println(result);
    }


    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);

        int
            sum , result =  nums[0] + nums[1] + nums[2];

        for (int i = 0; i < nums.length - 2 ; i++) {
            for (int j = i + 1 , k = nums.length - 1; j < k; ) {
                sum = nums[i] + nums[j] + nums[k];
                if (Math.abs(target - sum) < Math.abs(target-result)){{
                    result = sum;
                }}
                if ( sum > target){
                    k--;
                }else if (sum < target){
                    j++;
                }else {
                    return sum;
                }
            }

        }

        return result;

    }
}